//
//  HomeListView.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/11.
//

import UIKit
import BRPickerView
import DZNEmptyDataSet

class HomeListView: QICategoryView {
    
    private var timeBtn = UIButton()
    private var mianRongArr = [HealthyFacialListModel]()
    private var yingYangArr = [NutritionHealthListModel]()
    private var xingFuGanArr = [HappinessListModel]()
    private var shengHuoArr = [HappinessListModel]()
    private var yiLiaoBaoGaoArr = [MedicalReportsyListModel]()
    private var juJiaJianCeArr = [MedicalReportsyListModel]()
    private var dataArr = [String]()
    private var selectDate = ""

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        
        addUI()
    }
    
    var typeStr = "" {
        didSet {
            getData()
        }
    }
    private func getData() {
        
        if typeStr == "面容健康" {
            mianRongArr.removeAll()
            QINetworkManager.requestJson(urlStr: "/Project/face", method: .get, parameters: ["date": selectDate]) { json in
                print(json)
                self.mianRongArr = json.arrayObject?.kj.modelArray(HealthyFacialListModel.self) ?? [HealthyFacialListModel]()
                self.tableView.reloadData()
            }
        } else if typeStr == "营养健康" {
            yingYangArr.removeAll()
            
            QINetworkManager.requestJson(urlStr: "/project/healthStatistics", parameters: nil) { json in
//                print(json)
                let today = self.getPercentageModel(json: json["today"])
//                let near_seven_days = self.getPercentageModel(json: json["near_seven_days"])
                
                let childModel = NutritionHealthModel()
                var model = NutritionHealthListModel()
                model.list = [childModel]
                model.energy = today
                model.date = "今天"
                self.yingYangArr.append(model)
//                model.date = "最近七天"
//                model.energy = near_seven_days
//                self.yingYangArr.append(model)
                
                
                QINetworkManager.requestJson(urlStr: "/Project/health", method: .get, parameters: ["date": self.selectDate]) { json in
                    print(json)
                    
                    self.yingYangArr += json.arrayObject?.kj.modelArray(NutritionHealthListModel.self) ?? [NutritionHealthListModel]()
                    self.tableView.reloadData()
                }
            }
        } else if typeStr == "幸福感" {
            xingFuGanArr.removeAll()
            QINetworkManager.requestJson(urlStr: "/Project/happy", method: .get, parameters: ["date": selectDate]) { json in
                print(json)
                self.xingFuGanArr = json.arrayObject?.kj.modelArray(HappinessListModel.self) ?? [HappinessListModel]()
                self.tableView.reloadData()
            }
        } else if typeStr == "生活方式" {
            shengHuoArr.removeAll()
            QINetworkManager.requestJson(urlStr: "/Project/life", method: .get, parameters: ["date": selectDate]) { json in
                print(json)
                self.shengHuoArr = json.arrayObject?.kj.modelArray(HappinessListModel.self) ?? [HappinessListModel]()
                self.tableView.reloadData()
            }
        } else if typeStr == "医疗报告" {
            shengHuoArr.removeAll()
            QINetworkManager.requestJson(urlStr: "/Project/medical", method: .get, parameters: [:]) { json in
                print(json)
                self.yiLiaoBaoGaoArr = json.arrayObject?.kj.modelArray(MedicalReportsyListModel.self) ?? [MedicalReportsyListModel]()
                self.tableView.reloadData()
            }
        } else if typeStr == "居家检测" {
            shengHuoArr.removeAll()
            QINetworkManager.requestJson(urlStr: "/Project/room", method: .get, parameters: [:]) { json in
                print(json)
                self.juJiaJianCeArr = json.arrayObject?.kj.modelArray(MedicalReportsyListModel.self) ?? [MedicalReportsyListModel]()
                self.tableView.reloadData()
            }
        }
    }
    
    private func addUI() {
        let currentDate = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM"
        selectDate = dateFormatter.string(from: currentDate)
        
        timeBtn = UIButton().then {
            $0.frame = CGRect(x: 20, y: 0, width: 100, height: 40)
            $0.titleLabel?.font = SYSFONTBOLD(ofSize: 14)
            $0.setTitle(selectDate, for: .normal)
            $0.setTitleColor(Color333333, for: .normal)
            $0.setImage(UIImage(named: "箭头下"), for: .normal)
            $0.addTarget(self, action: #selector(timeBtnClick), for: .touchUpInside)
        }
        self.addSubview(timeBtn)
        timeBtn.setButtonImagePosition(.right, spacing: 5)
        
        self.addSubview(tableView)
    }
    
    @objc private func timeBtnClick() {
        let dateView = BRDatePickerView()
        dateView.pickerMode = .YM
        dateView.title = "选择日期"
        dateView.resultBlock = {selectDate, selectValue in
            print(selectValue ?? "")
            self.selectDate = selectValue ?? "2024-01"
            self.timeBtn.setTitle(self.selectDate, for: .normal)
            self.timeBtn.setButtonImagePosition(.right, spacing: 5)
            self.getData()
        }
        dateView.show()
    }
    
    private func getPercentageModel(json: JSON) -> [QINutritionHealthEnergyModel] {
        var modelArr = [QINutritionHealthEnergyModel]()
        
        let titleArr = ["能量(千卡)", "蛋白质(克)", "碳水化合物(克)", "脂肪(克)", "膳食纤维(克)", "糖(克)", "饱和脂肪(克)", "反式脂肪(克)", "胆固醇(毫克)", "钙(毫克)", "铜(毫克)", "铁(毫克)", "镁(毫克)", "锰(毫克)", "磷(毫克)", "钾(毫克)", "钠(毫克)", "锌(毫克)", "维生素C(毫克)"]
        for (index, titleStr) in titleArr.enumerated() {
            var model = QINutritionHealthEnergyModel()
            model.title = titleStr
            if index == 0 {
                model.percentage = json["energy"].stringValue
            } else if index == 1 {
                model.percentage = json["protein"].stringValue
            } else if index == 2 {
                model.percentage = json["carbohydrates"].stringValue
            } else if index == 3 {
                model.percentage = json["fat"].stringValue
            } else if index == 4 {
                model.percentage = json["dietary_fiber"].stringValue
            } else if index == 5 {
                model.percentage = json["sugar"].stringValue
            } else if index == 6 {
                model.percentage = json["saturated"].stringValue
            } else if index == 7 {
                model.percentage = json["trans_fat"].stringValue
            } else if index == 8 {
                model.percentage = json["cholesterol"].stringValue
            } else if index == 9 {
                model.percentage = json["calcium"].stringValue
            } else if index == 10 {
                model.percentage = json["copper"].stringValue
            } else if index == 11 {
                model.percentage = json["iron"].stringValue
            } else if index == 12 {
                model.percentage = json["magnesium"].stringValue
            } else if index == 13 {
                model.percentage = json["manganese"].stringValue
            } else if index == 14 {
                model.percentage = json["phosphorus"].stringValue
            } else if index == 15 {
                model.percentage = json["potassium"].stringValue
            } else if index == 16 {
                model.percentage = json["sodium"].stringValue
            } else if index == 17 {
                model.percentage = json["zinc"].stringValue
            } else if index == 18 {
                model.percentage = json["vitamin_c"].stringValue
            }
            
            modelArr.append(model)
        }
        
        
        return modelArr
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: 40, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 80)
        tableView.backgroundColor = ColorEEEEEE
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()

}

extension HomeListView: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if typeStr == "面容健康" {
            return mianRongArr.count
        } else if typeStr == "营养健康" {
            return yingYangArr.count
        } else if typeStr == "幸福感" {
            return xingFuGanArr.count
        } else if typeStr == "生活方式" {
            return shengHuoArr.count
        } else if typeStr == "医疗报告" {
            return yiLiaoBaoGaoArr.count
        } else if typeStr == "居家检测" {
            return juJiaJianCeArr.count
        } else {
            return dataArr.count
        }
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if typeStr == "面容健康" {
            return mianRongArr[section].date
        } else if typeStr == "营养健康" {
            return yingYangArr[section].date
        } else if typeStr == "幸福感" {
            return xingFuGanArr[section].date
        } else if typeStr == "生活方式" {
            return shengHuoArr[section].date
        } else if typeStr == "医疗报告" {
            return yiLiaoBaoGaoArr[section].date
        } else if typeStr == "居家检测" {
            return juJiaJianCeArr[section].date
        } else {
            return ""
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if typeStr == "面容健康" {
            let model = mianRongArr[section]
            return model.list.count
        } else if typeStr == "营养健康" {
            let model = yingYangArr[section]
            return model.list.count
        } else if typeStr == "幸福感" {
            let model = xingFuGanArr[section]
            return model.list.count
        } else if typeStr == "生活方式" {
            let model = shengHuoArr[section]
            return model.list.count
        } else if typeStr == "医疗报告" {
            return yiLiaoBaoGaoArr[section].list.count
        } else if typeStr == "居家检测" {
            return juJiaJianCeArr[section].list.count
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if typeStr == "幸福感" || typeStr == "生活方式" {
            return 50
        } else {
            return 110
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if typeStr == "面容健康" {
            let cell = HomeListViewCell()
            cell.selectionStyle = .none
            cell.mianRongModel = mianRongArr[indexPath.section].list[indexPath.row]
            return cell
        } else if typeStr == "营养健康" {
            if indexPath.section > 0 {
                let cell = HomeListViewCell()
                cell.selectionStyle = .none
                cell.yingyangModel = yingYangArr[indexPath.section].list[indexPath.row]
                cell.deleteBlock = {
//                    if self.yingYangArr[indexPath.section].list.count > indexPath.row {
//                        self.yingYangArr[indexPath.section].list.remove(at: indexPath.row)
//                        tableView.reloadData()
//                    }
                    self.getData()
                }
                return cell
            } else {
                let cell = QINutritionHealthCell()
                cell.selectionStyle = .none
                cell.modelArr = yingYangArr[indexPath.section].energy
                return cell
            }
        } else if typeStr == "幸福感" {
            let cell = HomeListTextViewCell()
            cell.selectionStyle = .none
            cell.xingFuGanModel = xingFuGanArr[indexPath.section].list[indexPath.row]
            return cell
        } else if typeStr == "生活方式" {
            let cell = HomeListTextViewCell()
            cell.selectionStyle = .none
            cell.xingFuGanModel = shengHuoArr[indexPath.section].list[indexPath.row]
            return cell
        } else if typeStr == "医疗报告" {
            let cell = HomeListViewCell()
            cell.selectionStyle = .none
            cell.yiLiaoBaoGaoModel = yiLiaoBaoGaoArr[indexPath.section].list[indexPath.row]
            return cell
        } else if typeStr == "居家检测" {
            let cell = HomeListViewCell()
            cell.selectionStyle = .none
            cell.yiLiaoBaoGaoModel = juJiaJianCeArr[indexPath.section].list[indexPath.row]
            return cell
        } else {
            let cell = HomeListViewCell()
            cell.selectionStyle = .none
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if typeStr == "面容健康" {
            let ctl = HealthyFacialDetailViewController()
            ctl.model = mianRongArr[indexPath.section].list[indexPath.row]
            navigationController?.pushViewController(ctl, animated: true)
        } else if typeStr == "营养健康" {
            let ctl = NutritionHealthDetailViewCtl()
            ctl.model = yingYangArr[indexPath.section].list[indexPath.row]
            navigationController?.pushViewController(ctl, animated: true)
        } else if typeStr == "幸福感" {
            let model = xingFuGanArr[indexPath.section].list[indexPath.row]
            let ctl = AnswerListViewController()
            ctl.problemID = model.id
            ctl.typeStr = typeStr
            navigationController?.pushViewController(ctl, animated: true)
        } else if typeStr == "生活方式" {
            let model = shengHuoArr[indexPath.section].list[indexPath.row]
            let ctl = AnswerListViewController()
            ctl.problemID = model.id
            ctl.typeStr = typeStr
            navigationController?.pushViewController(ctl, animated: true)
        } else if typeStr == "医疗报告" {
            let ctl = TextResultDisplayViewController()
            ctl.typeStr = typeStr
            ctl.model = yiLiaoBaoGaoArr[indexPath.section].list[indexPath.row]
            navigationController?.pushViewController(ctl, animated: true)
        } else if typeStr == "居家检测" {
            let ctl = TextResultDisplayViewController()
            ctl.typeStr = typeStr
            ctl.model = juJiaJianCeArr[indexPath.section].list[indexPath.row]
            navigationController?.pushViewController(ctl, animated: true)
        } else {
            
        }
    }
    
}

extension HomeListView: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate{
    
    // 是否显示DZNEmptyDataSet这个控件
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        if typeStr == "面容健康" {
            return mianRongArr.count > 0 ? false : true
        } else if typeStr == "营养健康" {
            return yingYangArr.count > 0 ? false : true
        } else if typeStr == "幸福感" {
            return xingFuGanArr.count > 0 ? false : true
        } else if typeStr == "生活方式" {
            return shengHuoArr.count > 0 ? false : true
        } else {
            return dataArr.count > 0 ? false : true
        }
    }
    
    // 显示的背景图
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: "暂无数据")
    }
    
    func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControl.State) -> NSAttributedString! {
        let attStr = NSMutableAttributedString(string: "当前暂无记录请尽快进行AI健康分析")
        let rang: NSRange = NSRange(location: 0, length: attStr.length)
        attStr.addAttribute(NSAttributedString.Key.font, value: SYSFONT(ofSize: 14), range: rang)
        attStr.addAttribute(NSAttributedString.Key.foregroundColor, value: Color999999, range: rang)
        return attStr
    }
    
    
}




class HomeListViewCell: UITableViewCell {
    
    var deleteBlock: voidBlock!
    private var imgView = UIImageView()
    private var titleL = YYLabel()
    private var weightL = YYLabel()
    private var deleteBtn = UIButton()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = ColorEEEEEE
        addUI()
    }
    func addUI() {
        
        let bgView = UIView()
        bgView.frame = CGRect(x: 16, y: 5, width: SCREEN_WIDTH - 32, height: 100)
        bgView.backgroundColor = .white
        bgView.addRoundedCorners(withRadius: 10)
        contentView.addSubview(bgView)
        
        imgView = UIImageView().then {
            $0.frame = CGRect(x: 10, y: 10, width: 80, height: 80)
            $0.image = UIImage(named: "noo")
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
            $0.addRoundedCorners(withRadius: 5)
        }
        bgView.addSubview(imgView)
        
        titleL = YYLabel().then({
            $0.frame = CGRect(x: imgView.right + 10, y: 15, width: bgView.width - 110, height: 70)
            $0.text = ""
            $0.textVerticalAlignment = .top
            $0.numberOfLines = 0
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
        })
        bgView.addSubview(titleL)
        let att = NSMutableAttributedString(string: "平时要留意身体的变化，为健康负责。那些有疾病在发展的人会发现自己的嘴唇颜色改变...")
        att.yy_lineSpacing = 8
        att.yy_font = SYSFONT(ofSize: 14)
        titleL.attributedText = att
        
        weightL = YYLabel().then({
            $0.frame = CGRect(x: bgView.width - 60, y: 15, width: 50, height: 70)
            $0.text = ""
            $0.isHidden = true
            $0.textAlignment = .right
            $0.textVerticalAlignment = .top
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
        })
        bgView.addSubview(weightL)
        
        deleteBtn = UIButton().then {
            $0.frame = CGRect(x: imgView.right + 10, y: bgView.bottom - 40, width: 40, height: 40)
            $0.titleLabel?.font = FONTBOLD(ofSize: 14)
            $0.isHidden = true
            $0.setTitle("删除", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addTarget(self, action: #selector(deleteBtnClick), for: .touchUpInside)
        }
        bgView.addSubview(deleteBtn)
        
        let detailL = UILabel().then({
            $0.frame = CGRect(x: bgView.width - 60, y: bgView.bottom - 40, width: 50, height: 40)
            $0.text = "详情"
            $0.textAlignment = .right
            $0.textColor = MainColor
            $0.font = FONT(ofSize: 13)
        })
        bgView.addSubview(detailL)
    }
    
    @objc private func deleteBtnClick() {
        QINetworkManager.requestJson(urlStr: "/Project/delete", parameters: ["id": yingyangModel.health.id]) { json in
            print(json)
            ShowHUD(str: "删除成功")
            if self.deleteBlock != nil {
                self.deleteBlock()
            }
        }
    }
    
    /// 面容健康
    var mianRongModel = HealthyFacialModel() {
        didSet {
            imgView.kf.setImage(with: URL(string: "\(IMAGE_URL)\(mianRongModel.image)"))
            titleL.text = mianRongModel.face_age
        }
    }
    /// 营养健康
    var yingyangModel = NutritionHealthModel() {
        didSet {
            deleteBtn.isHidden = false
            imgView.kf.setImage(with: URL(string: yingyangModel.health.image))
            titleL.text = yingyangModel.name
            weightL.isHidden = false
            
            let arr = yingyangModel.button_on_or_off.components(separatedBy: ",")
            guard arr.count >= 3 else {
                return
            }
            if arr[0] == "1" && yingyangModel.nutrtion.weight != "0" && yingyangModel.nutrtion.weight != ""{
                weightL.text = "\(yingyangModel.nutrtion.weight)g"
            } else if arr[1] == "1" && yingyangModel.nutrtion.capacity != "" {
                weightL.text = "\(yingyangModel.nutrtion.capacity)ml"
            } else if arr[2] == "1" && yingyangModel.nutrtion.palm_size != "" {
                weightL.text = "\(yingyangModel.nutrtion.palm_size)手掌"
            }
            
        }
    }
    /// 幸福感
    var xingFuGanModel = HappinessModel() {
        didSet {
//            imgView.kf.setImage(with: URL(string: "\(IMAGE_URL)\(xingFuGanModel.health.image)"))
            titleL.text = xingFuGanModel.text
        }
    }
    /// 医疗报告
    var yiLiaoBaoGaoModel = MedicalReportsyModel() {
        didSet {
            imgView.kf.setImage(with: URL(string: "\(IMAGE_URL)\(yiLiaoBaoGaoModel.image)"))
            titleL.text = yiLiaoBaoGaoModel.predict
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


class HomeListTextViewCell: UITableViewCell {
    
    private var titleL = YYLabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = ColorEEEEEE
        addUI()
    }
    func addUI() {
        
        let bgView = UIView()
        bgView.frame = CGRect(x: 16, y: 5, width: SCREEN_WIDTH - 32, height: 40)
        bgView.backgroundColor = .white
        bgView.addRoundedCorners(withRadius: 10)
        contentView.addSubview(bgView)
        
        titleL = YYLabel().then({
            $0.frame = CGRect(x: 10, y: 5, width: bgView.width - 20, height: 30)
            $0.text = ""
            $0.textVerticalAlignment = .center
            $0.numberOfLines = 0
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
        })
        bgView.addSubview(titleL)
        
        
        let att = NSMutableAttributedString(string: "平时要留意身体的变化，为健康负责。那些有疾病在发展的人会发现自己的嘴唇颜色改变...")
        att.yy_lineSpacing = 8
        att.yy_font = SYSFONT(ofSize: 14)
        titleL.attributedText = att
    }
    
    /// 幸福感
    var xingFuGanModel = HappinessModel() {
        didSet {
            titleL.text = xingFuGanModel.text
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


class QINutritionHealthCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addUI()
    }
    func addUI() {
        self.backgroundColor = ColorEEEEEE
        
        let bgView = UIView()
        bgView.frame = CGRect(x: 10, y: 0, width: SCREEN_WIDTH - 20, height: 110)
        bgView.backgroundColor = .white
        bgView.addRoundedCorners(withRadius: 8)
        self.contentView.addSubview(bgView)
        
        bgView.addSubview(tableView)
        
//        let rightView = QISliderView()
//        rightView.frame = CGRect(x: bgView.width - 30, y: 15, width: 20, height: 80)
//        rightView.backgroundColor = ColorEEEEEE
//        rightView.addRoundedCorners(withRadius: 2)
//        bgView.addSubview(rightView)
        
    }
    
    var modelArr = [QINutritionHealthEnergyModel]() {
        didSet {
            tableView.reloadData()
        }
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH - 20, height: 110)
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
//        tableView.alwaysBounceVertical = true
//        tableView.alwaysBounceHorizontal = true
        tableView.showsVerticalScrollIndicator = true
        tableView.addRoundedCorners(withRadius: 8)
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension QINutritionHealthCell: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return modelArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = QINutritionHealthElementCell()
        cell.selectionStyle = .none
        cell.model = modelArr[indexPath.row]
        return cell
    }
    
}

class QINutritionHealthElementCell: UITableViewCell {
    
    private var titleL = UILabel()
    private let bgView = UIView()
    private var linView = UIView()
    private var percentageL = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addUI()
    }
    func addUI() {
        
        titleL = UILabel().then({
            $0.frame = CGRect(x: 10, y: 10, width: 300, height: 17)
            $0.text = "卡路里"
            $0.textColor = .black
            $0.font = FONTBOLD(ofSize: 12)
        })
        self.addSubview(titleL)
        
        bgView.frame = CGRect(x: 10, y: titleL.bottom, width: 270, height: 10)
        bgView.backgroundColor = ColorWithStr("#FFE8EA")
        bgView.addRoundedCorners(withRadius: 5)
        self.addSubview(bgView)
        
        linView = UIView()
        linView.frame = CGRect(x: 0, y: 0, width: 200, height: 10)
        linView.backgroundColor = MainColor
        bgView.addRoundedCorners(withRadius: 5)
        bgView.addSubview(linView)
        
        percentageL = UILabel().then({
            $0.frame = CGRect(x: 180, y: bgView.bottom, width: 70, height: 13)
            $0.text = "70%"
            $0.textColor = MainColor
            $0.textAlignment = .center
            $0.font = FONTBOLD(ofSize: 12)
        })
        self.addSubview(percentageL)
        
    }
    
    var model = QINutritionHealthEnergyModel() {
        didSet {
            var percentage = Int(model.percentage) ?? 0
            percentage = percentage > 100 ? 100 : percentage
            titleL.text = model.title
            percentageL.text = "\(percentage)%"
            
            let test = Double(percentage) / 100.0
            linView.frame = CGRect(x: 0, y: 0, width: 270 * test, height: 10)
            percentageL.frame = CGRect(x: 270 * test - 20, y: bgView.bottom, width: 70, height: 13)
            
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


class QISliderView: UIView {
    private let lineView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        lineView.frame = CGRect(x: 2, y: 0, width: 16, height: 6)
        lineView.backgroundColor = MainColor
        self.addSubview(lineView)
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: self)
            print("移动触摸：x = \(location.x), y = \(location.y)")
            lineView.y = location.y
            
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

